
import { useState, useActionState } from 'react'

async function increment(previousState: any, formData: any) {
  // formData.get('read')获取指定标单项的值
  // https://developer.mozilla.org/zh-CN/docs/Web/API/FormData
  let item: { [key: string]: any } = {}
  for (var value of formData.entries()) {
    console.log('c', value);
    item[`${value[0]}`] = value[1]
  }

  return {
    ...previousState,
    ...item,
  };
}

function Index() {
  const [info, setInfo] = useState({
    read: '',
    name: ''
  })
  const [state, formAction] = useActionState(increment, { read: 0 });

  const handleChange = (key: string, val: any) => {
    setInfo(values => ({
      ...values,
      [`${key}`]: val
    }))
  }

  return (
    <form action={formAction}>
      <input name='read' value={info.read} onChange={e => handleChange('read', e.target.value)} />
      <input name='name' value={info.name} onChange={e => handleChange('name', e.target.value)} />
      {state.read}
      <button type='submit'>Increment</button>
    </form>
  )
}

export default Index;